package com.c4p.im.session;

import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

public class RedisUserNetStore implements IUserNetStore {

    private RedisTemplate redisTemplate;

    public RedisUserNetStore(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 保存【用户-机器地址】的关联关系
     * @param userId
     * @param address
     * @param port
     */
    @Override
    public void put(String userId, String address, String port) {
        this.redisTemplate.opsForValue().set(
                getKey(userId), address + ":" + port, Duration.ofSeconds(60 * 5)
        );
    }

    @Override
    public String get(String userId) {
        Object value = this.redisTemplate.opsForValue().get(getKey(userId));
        return value == null ? null : (String) value;
    }

    @Override
    public void remove(String userId) {
        this.redisTemplate.delete(getKey(userId));
    }

    @Override
    public String getKey(String key) {
        return "websocket" + key;
    }
}
